﻿using Arch.EntityFrameworkCore.UnitOfWork.Collections;
using MyTodo.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyTodo.Shared.Parameters;
using MyTodo.Shared.Services;

namespace MyTodo.Services;

public class ServiceBase<TEntity> : IServiceBase<TEntity> where TEntity : class
{
    private readonly HttpRestClient _client;
    private readonly string _serviceName;

    public ServiceBase(HttpRestClient client, string serviceName)
    {
        _client = client;
        _serviceName = serviceName;
    }

    public async Task<ApiResponse<TEntity>> AddAsync(TEntity entity)
    {
        BaseRequest request = new BaseRequest()
        {
            Method = RestSharp.Method.Post,
            Route = $"api/{_serviceName}/Add",
            Parameter = entity
        };
       return await _client.ExecuteAsync<TEntity>(request);
    }

    public async Task<ApiResponse> DeleteAsync(int id)
    {
        BaseRequest request = new BaseRequest()
        {
            Method = RestSharp.Method.Delete,
            Route = $"api/{_serviceName}/Delete?id={id}"
        };
        return await _client.ExecuteAsync(request);
    }

    public async Task<ApiResponse<PagedList<TEntity>>> GetAllAsync(QueryParameter parameter)
    {
        BaseRequest request = new BaseRequest()
        {
            Method = RestSharp.Method.Get,
            Route = $"api/{_serviceName}/GetAll?PageIndex={parameter.PageIndex}&PageSize={parameter.PageSize}&Search={parameter.Search}"
        };
        return await _client.ExecuteAsync<PagedList<TEntity>>(request);
    }

    public async Task<ApiResponse<TEntity>> GetFirstOfDefaultAsync(int id)
    {
        BaseRequest request = new BaseRequest()
        {
            Method = RestSharp.Method.Get,
            Route = $"api/{_serviceName}/Get?id={id}"
        };
        return await _client.ExecuteAsync<TEntity>(request);
    }

    public async Task<ApiResponse<TEntity>> UpdateAsync(TEntity entity)
    {
        BaseRequest request = new BaseRequest()
        {
            Method = RestSharp.Method.Post,
            Route = $"api/{_serviceName}/Update",
            Parameter = entity
        };
        return await _client.ExecuteAsync<TEntity>(request);
    }
}
